package com.ys.controller.api.finance;

import com.bo.dto.NameValueDto;
import com.ys.config.MenuId;
import com.ys.entity.finance.TcwCompanyAccountTransfer;
import com.ys.entity.sys.YsCol;
import com.ys.service.finance.TcwCompanyAccountTransferService;
import com.ys.service.flow.YspTaskService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.PdfService;
import com.ys.service.sys.UploadService;
import com.ys.util.ExportExcelUtils;
import com.ys.util.admin.ConditionUtil;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 公司账户资金转账
 */
@Controller
@RequestMapping("/api/inter/tcwCompanyAccountTransfer")
public class ApiInterTcwCompanyAccountTransferController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterTcwCompanyAccountTransferController.class);

    @Autowired
    private CommonApiService<TcwCompanyAccountTransfer> commonApiService;

    @Autowired
    private TcwCompanyAccountTransferService tcwCompanyAccountTransferService;

    @Autowired
    private YspTaskService yspTaskService;

    @Autowired
    private PdfService pdfService;

    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public TcwCompanyAccountTransfer setSeachSql(TcwCompanyAccountTransfer cond){

        cond    .addLeftJoin("TS_UserChange U ON U.Id = A.CreateChangeId ")
                .addField("U.UserId + '/' + U.UserName AS _ys_createUserName")//制单人
                .addLeftJoin("YS_ProcInst P ON P.Bid = A.Bid ")
                .addField("CASE WHEN P.UpdateTime IS NULL AND A.EffectStock = 1 THEN FORMAT(A.UpdateTime, 'yyyy-MM-dd HH:mm:ss') ELSE FORMAT(P.UpdateTime, 'yyyy-MM-dd HH:mm:ss') END auditingTime")//审核时间
                .addLeftJoin("TCW_CompanyAccountTransferItem B ON B.Pbid=A.Bid")
                .addField("B.remark premark,B.vidOut vidOut,B.vyhzhmcOut vyhzhmcOut,B.vkhhOut vkhhOut,B.vyhzhOut vyhzhOut," +
                        "B.vidIn vidIn,B.vyhzhmcIn vyhzhmcIn,B.vkhhIn vkhhIn,B.vyhzhIn vyhzhIn,B.BaseInfoType baseInfoType,B.Amount amount")
                //排序
                .setOrderby("A.Bid DESC");

        cond = commonApiService.dataAuth(MenuId.TCW_CompanyAccountTransfer, cond);
        return  cond;
    }

    /**
     * 查询
     */
    @RequiresPermissions("tcwCompanyAccountTransfer:view")
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
                                 @ModelAttribute TcwCompanyAccountTransfer cond, String conditions
    ){
        try {
            cond = setSeachSql(cond);
            //查询条件
            String nameLinked = ConditionUtil.getConditionValue(conditions, "_ys_createUserName");//制单人
            if (nameLinked != null){
                cond.where("U.UserId LIKE '%" + nameLinked + "%'" + " OR  U.UserName LIKE '%" + nameLinked + "%'");
            }
            LayuiTableVoJA setList = commonApiService.searchLay(cond);

            return setList;
        }catch (Exception e){
            logger.error("查询出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }

    /*
     * 新增
     */
    @RequestMapping("/toAdd")
    @ResponseBody
    public R toAdd(HttpServletRequest request, @RequestParam Map<String, Object> params
    ) {
        try {
            logger.info("公司账户资金转账新增传参：" + params);
            //修改
            return tcwCompanyAccountTransferService.add(params);
        } catch (Exception e) {
            logger.error("公司账户资金转账新增出错：", e.getMessage(), e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }

    /**
     * 修改
     */
    @RequestMapping("/toEdit")
    @ResponseBody
    public R toEdit(HttpServletRequest request, @RequestParam Map<String, Object> params,String bid,String subData
    ) {
        try {
            logger.info("公司账户资金转账修改传参：" + params);
            //修改
            return tcwCompanyAccountTransferService.edit(bid,params);
        } catch (Exception e) {
            logger.error("公司账户资金转账修改出错：", e.getMessage(), e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }


    /**
     * 删除
     * @throws Exception
     */
    @PostMapping("/delete")
    @ResponseBody
    public R delete(Long id){

        try {
            return tcwCompanyAccountTransferService.deleteTrue(id);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("操作失败，请联系客服");
        }
    }
    /**
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TcwCompanyAccountTransfer cond, String conditions){
        try {
            cond.setPage(0).setSize(999999);
            cond = setSeachSql(cond);
            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(MenuId.TCW_CompanyAccountTransfer)
                    .setFrontShow(1)
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();
            //查询条件
            String nameLinked = ConditionUtil.getConditionValue(conditions, "_ys_createUserName");//制单人
            if (nameLinked != null){
                cond.where("U.UserId LIKE '%" + nameLinked + "%'" + " OR  U.UserName LIKE '%" + nameLinked + "%'");
            }
            //处理数据
            ExportExcelUtils<TcwCompanyAccountTransfer> util = new ExportExcelUtils<>(new TcwCompanyAccountTransfer());
            String toFilePath = util.exportExcel(listData, listField, "公司账户资金转账");
            UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }

    /**
     * 删除列表
     */
    @RequiresPermissions("tcwCompanyAccountTransferState:add")
    @RequestMapping("/toDelByItem")
    @ResponseBody
    public R toDelByItem(HttpServletRequest request,@RequestParam("list") List<String> idList){
        try {
            //删除
            for (int i = 0; i < idList.size(); i++) {
                tcwCompanyAccountTransferService.toDelByItem(Long.parseLong(idList.get(i)));
            }
            return R.ok();
        } catch (Exception e) {
            logger.error("删除出错：",e.getMessage(),e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }
    /**
     * 流转通过
     */
    @RequiresPermissions("tcwCompanyAccountTransfer:add")
    @PostMapping("/flowPass")
    @ResponseBody
    public R flowPass(HttpServletRequest request, Long id){
        try {
            TcwCompanyAccountTransfer entity = new TcwCompanyAccountTransfer().setId(id).queryFirst();
            return tcwCompanyAccountTransferService.flowPass(entity.getBid(), ShiroUtils.getUserId());
        } catch (IllegalArgumentException e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(e.getCause().getMessage());
        }
    }

    /**
     * 流转退回
     */
    @RequiresPermissions("tcwCompanyAccountTransfer:add")
    @PostMapping("/flowRefuse")
    @ResponseBody
    public R flowRefuse(HttpServletRequest request, Long id, String reason){
        try {
            TcwCompanyAccountTransfer entity = new TcwCompanyAccountTransfer().setId(id).queryFirst();
            return yspTaskService.flowRefuse(entity.getBid(), reason, ShiroUtils.getUserId());
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(e.getCause().getMessage());
        }
    }



    /**
     * 流转驳回
     */
    @RequiresPermissions("tcwCompanyAccountTransfer:add")
    @PostMapping("/flowInit")
    @ResponseBody
    public R flowInit(HttpServletRequest request, Long id, String reason){
        try {
            TcwCompanyAccountTransfer entity = new TcwCompanyAccountTransfer().setId(id).queryFirst();
            return yspTaskService.flowInit(entity.getBid(), reason, ShiroUtils.getUserId());
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(e.getCause().getMessage());
        }
    }


    /**
     * 打印 2024-10-15
     * @param params
     * @throws Exception
     * @Author: fxz
     */
    @RequestMapping("/exportdy")
    @ResponseBody
    public R exportdy(HttpServletRequest request,@RequestParam Map<String, Object> params) throws Exception{
        String bid = params.get("bid").toString();
        List<Map<String,Object>> infoList = new TcwCompanyAccountTransfer()
                .addLeftJoin("TB_CompanyInfo G ON G.vid=A.CompanyVid")
                .addField("G.Vname vName")
                .addLeftJoin("TS_UserChange U ON U.Id = A.CreateChangeId ")
                .addField("U.UserId + '/' + U.UserName AS _ys_createUserName")//制单人
                .addField("U.DeptName AS deptName")//制单人部门
                .addField("FORMAT(A.CreateTime, 'yyyy-MM-dd HH:mm:ss') AS createTimeByStr")//创建时间
                .addLeftJoin("YS_ProcInst P ON P.Bid = A.Bid ")
                .addField("CASE WHEN P.UpdateTime IS NULL AND A.EffectStock = 1 THEN FORMAT(A.UpdateTime, 'yyyy-MM-dd HH:mm:ss') ELSE FORMAT(P.UpdateTime, 'yyyy-MM-dd HH:mm:ss') END auditingTime")//审核时间
                .addLeftJoin("TCW_CompanyAccountTransferItem B ON B.Pbid=A.Bid")
                .addField("B.remark premark,B.vidOut vidOut,B.vyhzhmcOut vyhzhmcOut,B.vkhhOut vkhhOut,B.vyhzhOut vyhzhOut," +
                        "B.vidIn vidIn,B.vyhzhmcIn vyhzhmcIn,B.vkhhIn vkhhIn,B.vyhzhIn vyhzhIn,B.BaseInfoType baseInfoType,B.Amount amount")
                .setBid(bid)
                .queryMap();

        if(infoList!=null && infoList.size()>0){
            Map<String,Object> sonByOne = infoList.get(0);

            BigDecimal sonAmountTotal = BigDecimal.ZERO;
            for (Map<String, Object> son : infoList){
                sonAmountTotal = sonAmountTotal.add(new BigDecimal(son.get("amount").toString()));
            }

            String nameStrIn =  (sonByOne.get("vyhzhmcIn")!=null ? sonByOne.get("vyhzhmcIn").toString():"")
                    + "/" + (sonByOne.get("vyhzhIn")!=null ? sonByOne.get("vyhzhIn").toString():"")
                    + "/" + (sonByOne.get("vkhhIn")!=null ? sonByOne.get("vkhhIn").toString():"");
            String nameStrOut =  (sonByOne.get("vyhzhmcOut")!=null ? sonByOne.get("vyhzhmcOut").toString():"")
                    + "/" + (sonByOne.get("vyhzhOut")!=null ? sonByOne.get("vyhzhOut").toString():"")
                    + "/" + (sonByOne.get("vkhhOut")!=null ? sonByOne.get("vkhhOut").toString():"");

            List<NameValueDto> listData = new ArrayList<>();
            listData.add(new NameValueDto("单据编号",bid));
            listData.add(new NameValueDto("申请人",sonByOne.get("_ys_createUserName").toString()));
//            listData.add(new NameValueDto("申请部门",sonByOne.get("deptName").toString()));
//            listData.add(new NameValueDto("付款账号",nameStrOut));
            listData.add(new NameValueDto("收款账号",nameStrIn));
            listData.add(new NameValueDto("付款类型","对公转账"));
            listData.add(new NameValueDto("付款金额",sonAmountTotal.toString()));
            listData.add(new NameValueDto("付款说明",sonByOne.get("remark").toString()));
            String url = pdfService.generatePDF(bid,"付款单", sonByOne.get("vName").toString(), sonByOne.get("createTimeByStr").toString(),listData);
            return R.ok(url);
        }else {
            return R.error("未查询到要导出的数据");
        }


    }
}
        










